package cn.fulong.sso.client.servlet;


import cn.fulong.sso.client.manager.SessionManager;
import cn.fulong.sso.client.utils.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @desc: 本地退出
 * @author: 云树
 * @createDate: 2019/1/16 20:55
 * @version: 1.0
 */
@Slf4j
public class LogoutServlet extends HttpServlet {

    private SessionManager sessionManager;

    private String ssoLogoutUrl;

    /**
     * 是否开启从请求头Referer信息获取请求地址，作为，退出成功后回跳转地址（自动从哪退出回哪去）
     */
    private boolean autoReturnUrl = false;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String sso_logout_url = ServletConfigUtil.getConfig(config, "sso_logout_url");
        if (StringSelfUtil.isBlank(sso_logout_url)) {
            String publicServer = ServletConfigUtil.getSSOPublicService(config);
            sso_logout_url = SsoUrlUtil.mergeUrl(publicServer, "logout");
        }
        String returnUrl = config.getInitParameter("return_url");
        this.autoReturnUrl = ServletConfigUtil.getBoolean(config, "auto_return_url");
        if (StringSelfUtil.isNotBlank(returnUrl)) {
            this.ssoLogoutUrl = SsoUrlUtil.addParams(sso_logout_url, "return_url", Base64Util.encode(returnUrl));
        } else {
            this.ssoLogoutUrl = sso_logout_url;
        }
        ServletContext servletContext = this.getServletContext();
        //获取SSo服务端全局配置
        this.sessionManager = SessionManagerUtils.getRegisterSessionMangerBean(servletContext);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession httpSession = req.getSession();
        try {
            if (!sessionManager.removeSessionManagerBySession(httpSession)) {
                try {
                    httpSession.invalidate();
                } catch (Exception ex) {

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                httpSession.invalidate();
            } catch (Exception ex) {

            }
        }
        String returnUrl = req.getParameter("return_url");
        String language = req.getParameter("language");
        Map<String, String> params = new HashMap(4);
        params.put("language", StringSelfUtil.isNotBlank(language) ? language : "ch");
        if (StringSelfUtil.isNotBlank(returnUrl)) {
            params.put("return_url", Base64Util.urlEncodeToBase64(returnUrl));
        }
        if (StringSelfUtil.isBlank(returnUrl) && autoReturnUrl) {
            //开启自动从请求头Referer信息获取请求地址，作为，退出成功后回跳转地址（自动从哪退出回哪去）
            String refererUrl = RequestUtil.getReferer(req);
            params.put("return_url", Base64Util.encode(refererUrl));
        }
        String ssoLogoutUrl = SsoUrlUtil.addParams(this.ssoLogoutUrl, params);
        resp.sendRedirect(ssoLogoutUrl);
    }

}
